package com.pat.jrgwt.client;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DoubleBox;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.FlexTable;
import com.pat.jrgwt.shared.MyConstants;

public class ProfitLossesView extends Composite 
{

    private static ProfitLossesViewUiBinder uiBinder = GWT.create(ProfitLossesViewUiBinder.class);
    
    protected @UiField FlexTable ProfitLossesGrid;
    
    protected ListBox m_lstYear = new ListBox();

    @SuppressWarnings("deprecation")
    protected int m_currentYear = new Date().getYear() + 1900;

    interface ProfitLossesViewUiBinder extends UiBinder<Widget, ProfitLossesView>
    {
    }

    private final static class SingletonHolder
    {
        private final static ProfitLossesView instance = new ProfitLossesView();
    }
    
    /**
     * Returns the only ProfitLossesView instance
     */
    public static ProfitLossesView getInstance()
    {
        return SingletonHolder.instance;
    }
    
    private ProfitLossesView()
    {
        initWidget(uiBinder.createAndBindUi(this));
        
        formatProfitLossesGrid();
        clearValueGrid();

//        loadInitialData();

//        recalculateProfitLossesTotal();
    }
    

    protected void formatProfitLossesGrid()
    {
        ProfitLossesGrid.setBorderWidth(1);

        formatYearsList();
        
        String[] exNames = m_holder.getExchangeNames();
        for (int i = 0; i < exNames.length; i++ )
        {
            ProfitLossesGrid.setText(0, i+1, exNames[i]);
            ProfitLossesGrid.getCellFormatter().addStyleName(0, i+1, "cellBold");
            ProfitLossesGrid.getCellFormatter().setWidth(0, i+1, "120px");
            for (int row = 1; row < 13; row++)
            {
                ProfitLossesGrid.setText(row, i+1, "");
            }
        }
        int columns = ProfitLossesGrid.getCellCount(0);
        ProfitLossesGrid.setText(0, columns, "Prufsumme");
        ProfitLossesGrid.getCellFormatter().addStyleName(0, columns, "cellBold");
        
        for (int month = 1; month < 13; month++)
        {
            ProfitLossesGrid.setText(month, 0, "" + month);
        }
    }


    /**
     * Formats list of years w/ change handler
     */
    @SuppressWarnings("deprecation")
    protected void formatYearsList()
    {
        Date now = new Date();
        int year = 0;
        GWT.log("Current year: " + m_currentYear);
        for (int i = 0; i < MyConstants.TOTAL_YEARS; i++)
        {
            year = now.getYear() + 1900 - MyConstants.TOTAL_YEARS + i + 1;
            m_lstYear.addItem("" + year);
            if( year == m_currentYear )
            {
                m_lstYear.setSelectedIndex(i);
            }
        }
        m_lstYear.addChangeHandler(new ChangeHandler()
        {
            
            @Override
            public void onChange(ChangeEvent event)
            {
                m_currentYear = Integer.parseInt(m_lstYear.getItemText(m_lstYear.getSelectedIndex()));
                ValuesStorage.getInstance().loadProfitLossesFx(m_currentYear);
            }
        });
        ProfitLossesGrid.setWidget(0, 0, m_lstYear);

    }

    /**
     * Redisplays initial values and calculates profit/losses
     */
    public void recalculate()
    {
        int col = 1;
        double v = 0;
        // Totals for each month
        double[] totals = new double[12];
        NumberFormat nf = NumberFormat.getFormat("###,##0.0");

        JrcEventsLog.getInstance().add("Recalculating profit/losses...");
        for(String exName : m_holder.getExchangeNames())
        {
            ProfitLossesGrid.setText(0, col, exName);
            for( int month = 1; month < 13; month++ )
            {
                v = m_holder.get(exName, month);
                if( v != Double.MIN_VALUE )
                {
                    ProfitLossesGrid.setText(month, col, nf.format(v));
                    // Calculate total of this month
                    totals[month - 1] += v;
                }
            }
            col++;
        }
        
        // Place of last column
        int column = ProfitLossesGrid.getCellCount(0) - 1;
        for( int month = 1; month < 13; month++ )
        {
            ProfitLossesGrid.setText(month, column, nf.format(totals[month - 1]));
        }
    }

    /**
     * Clears all values cells (sets values to "0.0")
     */
    public void clearValueGrid()
    {
        int columns = ProfitLossesGrid.getCellCount(0);
        for (int column = 1; column < columns; column++)
        {
            for (int row = 1; row < 13; row++)
            {
                ProfitLossesGrid.setText(row, column, "0.0");
            }
        }
    }


    protected ProfitLossesHolder m_holder = ValuesStorage.getInstance().getProfitLosses();
    protected void loadInitialData()
    {
        //HashMap<String, double[]> m_ar = new HashMap<String, double[]>();
        
        //ProfitLossesHolder m_hHolder = ;
    }


    public ProfitLossesView(String firstName)
    {
        initWidget(uiBinder.createAndBindUi(this));
    }
    

}
